import React, { FC, useEffect } from 'react';
import { Modal, Form, Input, message, Select } from 'antd';
import { addPlane } from '../../../Request';
import { Plane } from '../../../types/plane.type';

const Option = Select.Option;

type Props = {
    show: boolean;
    onOk: () => void;
    onCancel: () => void;
    selectedPlane?: Plane;
}
const FormItem = Form.Item;

export const RegistePlanModal: FC<Props> = ({ show, onOk, onCancel, selectedPlane }) => {
    const [form] = Form.useForm<Plane>();

    const onFinish = (values: Plane) => {
        if (selectedPlane){
            values.id = selectedPlane.id;
        }
        addPlane(values).then((data) => {
            if (!data) {
                message.error("Something went wrong!");
                return;
            }
            message.success(`Plane ${data.name} ${selectedPlane ? "modify" : "add"} success`);
            form.resetFields();
            onOk();
            onCancel();
        });
    };
    const handleOk = () => {
        form.submit();
    }
    return <Modal
        title="Plane Register"
        open={show}
        onOk={handleOk}
        onCancel={onCancel}
    >
        <div>
            <Form onFinish={onFinish} form={form} preserve={false} initialValues={selectedPlane}>
                <FormItem label="Plane Name" name="name">
                    <Input placeholder='Input plane name' />
                </FormItem>
                <FormItem label="Plane Color" name="color">
                    <Input placeholder='Input plane color' />
                </FormItem>
                <FormItem label="Description" name="description">
                    <Input placeholder='Input description' />
                </FormItem>
                <FormItem label="Status" name="status">
                    <Select placeholder='Select status'>
                        <Option value="0">0</Option>
                        <Option value="1">1</Option>
                        <Option value="2">2</Option>
                    </Select>
                </FormItem>
            </Form>
        </div>
    </Modal>
}